/*
 *  modifier: Honrun
 *  date:     2023/10/29 20:42
 */
#include "stdio.h"
#include "microList.h"


int8_t cMrListInit(MrListType *ptypeList, int64_t lValue)
{
    if(ptypeList == NULL)
        return -1;

    ptypeList->pNext = ptypeList->pPrevious = ptypeList;
    ptypeList->value = lValue;

    return 0;
}

/* 从小到大，顺序插入 */
int8_t cMrListInsert(MrListType *ptypeListHead, MrListType *ptypeListNew)
{
    MrListType *ptypeListNow = NULL;

    if((ptypeListHead == NULL) || (ptypeListNew == NULL))
        return -1;

    /* 找到排序插入的前一个位置 */
    for(ptypeListNow = ptypeListHead; ptypeListNow->pNext->value < ptypeListNew->value; ptypeListNow = ptypeListNow->pNext)
    {
        /* 链表最后一个节点 */
        if(ptypeListNow->pNext == ptypeListHead)
        {
            break;
        }
    }

    return cMrListInsertAfter(ptypeListNow, ptypeListNew);
}

/* 插入到之前 */
int8_t cMrListInsertBefore(MrListType *ptypeListBase, MrListType *ptypeListNew)
{
    if((ptypeListBase == NULL) || (ptypeListNew == NULL))
        return -1;

    ptypeListNew->pPrevious         = ptypeListBase->pPrevious;
    ptypeListBase->pPrevious->pNext = ptypeListNew;
    ptypeListBase->pPrevious        = ptypeListNew;
    ptypeListNew->pNext             = ptypeListBase;

    return 0;
}

/* 插入到之后 */
int8_t cMrListInsertAfter(MrListType *ptypeListBase, MrListType *ptypeListNew)
{
    if((ptypeListBase == NULL) || (ptypeListNew == NULL))
        return -1;

    ptypeListNew->pNext             = ptypeListBase->pNext;
    ptypeListBase->pNext->pPrevious = ptypeListNew;
    ptypeListBase->pNext            = ptypeListNew;
    ptypeListNew->pPrevious         = ptypeListBase;

    return 0;
}

/* 插入到第一个位置 */
int8_t cMrListInsertHead(MrListType *ptypeListHead, MrListType *ptypeListNew)
{
    return cMrListInsertAfter(ptypeListHead, ptypeListNew);
}

/* 插入到最后一个位置 */
int8_t cMrListInsertEnd(MrListType *ptypeListHead, MrListType *ptypeListNew)
{
    return cMrListInsertBefore(ptypeListHead, ptypeListNew);
}

/* 移除 */
int8_t cMrListRemove(MrListType *ptypeList)
{
    if(ptypeList == NULL)
        return -1;

    ptypeList->pPrevious->pNext = ptypeList->pNext;
    ptypeList->pNext->pPrevious = ptypeList->pPrevious;

    ptypeList->pNext = ptypeList->pPrevious = ptypeList;

    return 0;
}
